package com.jky.trial.service.impl;

import com.jky.trial.common.BaseResult;
import com.jky.trial.common.Constants;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.Pagination;
import com.jky.trial.common.jpush.JPushUtils;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.entity.*;
import com.jky.trial.mapper.RelationMapper;
import com.jky.trial.mapper.TaskMapper;
import com.jky.trial.mapper.TaskSampleMapper;
import com.jky.trial.service.*;
import com.jky.trial.vo.RecordVo;
import com.jky.trial.vo.TaskSampleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class TaskSampleServiceImpl implements TaskSampleService {
    private final TaskSampleMapper recordMapper;
    private final TaskMapper taskMapper;
    private final MsgService msgService;
    private final UserService userService;
    private final ProjectService projectService;
    private final RecordService recordService;
    private final RelationMapper relationMapper;


    @Autowired
    TaskSampleServiceImpl(
            TaskMapper taskMapper,
            RecordService recordService,
            TaskSampleMapper recordMapper,
                          UserService userService,
                          RelationMapper relationMapper,
                          MsgService msgService,
                          ProjectService projectService
                          ) {
        this.recordService = recordService;
        this.taskMapper = taskMapper;
        this.userService = userService;
        this.relationMapper = relationMapper;
        this.recordMapper = recordMapper;
        this.projectService = projectService;
        this.msgService = msgService;
    }


    @Override
    public BaseResult create(TaskSample record) {
        if(record.getProcessId()!=null){
            Record record1 =recordService.detail(record.getProcessId());
            record.setTaskId(record1.getTargetId());
            Task record2 =taskMapper.selectByPrimaryKey(record1.getTargetId());
            record.setProjectId(record2.getProjectId());
        }else if(record.getTaskId()!=null){
                Task record2 =taskMapper.selectByPrimaryKey(record.getTaskId());
                record.setProjectId(record2.getProjectId());
        }
        TaskSampleVo taskSampleVo =new TaskSampleVo();
        taskSampleVo.setTaskId(record.getTaskId());;
        taskSampleVo.setCreateAt(new Date());
        int num = (int)this.count(taskSampleVo);
        Task task = taskMapper.selectByPrimaryKey(record.getTaskId());
        //生成土样编号
        record.setNo(
                Constants.generateLimitNumberStr(task.getNo(),4)+"-"+
                        Constants.generateLimitNumberStr(num+1,2)
                );
        recordMapper.insertSelective(record);
        return new BaseResult(true, record);
    }

    @Override
    public int update(TaskSample record) {
        return recordMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 邮寄样品
     * @param record
     * @param user
     * @return
     */
    @Override
    public int send(TaskSample record, User user) {
        TaskSample taskSample = this.detail(record.getId());
        if (taskSample.getStatus() != DataStatus.TASK_SAMPLE_STATUS_NEED_SEND.getVal()
                || !record.getStatus().equals(DataStatus.TASK_SAMPLE_STATUS_NEED_SUBMIT.getVal())) {
            return 0;
        }
        int res =  recordMapper.updateByPrimaryKeySelective(record);
        if(res>0){ //邮寄了样品
            Project project = projectService.detail(taskSample.getProjectId());
            String content = "用户"+user.getName()+"邮寄了编号为"+taskSample.getNo()+"的样品";
            msgService.sendMsg(
                    user.getId(),
                    project.getTechDirector(),       //描述员
                    content,
                    record.getId(),     ///
                    DataStatus.MSG_TYPE_SAMPLE_SEND.getVal()
            );
            User descer =  userService.detail(project.getTechDirector());
            if(descer.getTechRegId()!=null){
                //推送通知
                JPushUtils.sendPush(descer.getTechRegId(),"邮寄样品",content);
            }

        }
        return res;
    }

    @Override
    public int confirm(TaskSampleVo record, User user) {
        if(record.getSampleIds().size()==0)return 0;
        record.getSampleIds().forEach(id->{
            record.setId(id);
            TaskSample taskSample = this.detail(id);
            if(!DataStatus.TASK_SAMPLE_STATUS_NEED_CONFIRMED.getVal().equals(taskSample.getStatus())){ //土样未确认
                record.setStatus(DataStatus.TASK_SAMPLE_STATUS_NEED_CONFIRMED.getVal());
                int res =  recordMapper.updateByPrimaryKeySelective(record);
                if(res>0){ //确认了样品
                    Project project = projectService.detail(taskSample.getProjectId());
                    String content ="用户"+user.getName()+"确认了编号为"+taskSample.getNo()+"的样品";
                    msgService.sendMsg(
                            user.getId(),                   //
                            project.getTechDirector(),       //发给技术员
                            content,
                            record.getId(),     ///
                            DataStatus.MSG_TYPE_CONFIRM_BILL_SAMPLE.getVal()
                    );
                    User descer =  userService.detail(project.getTechDirector());
                    if(descer.getTechRegId()!=null){
                        //推送通知
                        JPushUtils.sendPush(descer.getTechRegId(),"样品确认",content);
                    }
                }
            }

        });
        return 1;
    }

    @Override
    public int del(int id) {
        TaskSample task = new TaskSample();
        task.setId(id);
        return recordMapper.updateByPrimaryKey(task);
    }

    @Override
    public TaskSample detail(int id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    /**
     * 包含任务名称、项目名称的土样
     * @param id
     * @return
     */
    @Override
    public TaskSampleVo moreDetail(int id) {
        TaskSampleVo taskSampleVo = recordMapper.selectVoByPrimaryKey(id);
        Task task = taskMapper.selectByPrimaryKey(taskSampleVo.getTaskId());
        taskSampleVo.setTaskName(task.getName());
        Project project = projectService.detail(taskSampleVo.getProjectId());
        taskSampleVo.setProjectName(project.getName());
        return taskSampleVo;
    }

    @Override
    public List<TaskSampleVo> list(TaskSampleVo record) {
        return recordMapper.pageList(record);
    }

    /**
     * 按项目ID勘察点
     *
     * @param record
     * @return
     */
    @Override
    public ListResult page(TaskSampleVo record) {
        List<TaskSampleVo> list = list(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public ListResult billSample(Integer sourceId) {
        Relation relation = new Relation();
        relation.setType(DataStatus.RELATION_TYPE_BILL_SAMPLE.getVal());
        relation.setSourceId(sourceId);
        List<RecordVo> taskSamples = recordMapper.billSample(relation);
        ListResult res = new ListResult(true, taskSamples);

        return res;
    }
    @Override
    public ListResult bookSample(Integer bookId) {
        Relation relation = new Relation();
        relation.setType(DataStatus.RELATION_TYPE_BOOK_SAMPLE.getVal());
        relation.setSourceId(bookId);
        List<Relation>  list=relationMapper.list(relation);
        List<RecordVo>  taskSampleVos=new ArrayList<>();

        list.forEach(item->{
            relation.setSourceId(item.getTargetId());
            relation.setType(DataStatus.RELATION_TYPE_BOOK_SAMPLE.getVal());
            taskSampleVos.addAll(recordMapper.billSample(relation));
        });
        return new ListResult(true,taskSampleVos);
    }

    @Override
    public ListResult bookSamplev2(Integer sourceId) {
        Relation relation = new Relation();
        relation.setSourceId(sourceId);
        relation.setType(DataStatus.RELATION_TYPE_BOOK_SAMPLE.getVal());
        return new ListResult(true,recordMapper.billSample(relation));
    }

    @Override
    public long count(TaskSampleVo record) {
        TaskSampleExample recordExample = new TaskSampleExample();
        TaskSampleExample.Criteria criteria = recordExample.createCriteria();
        if (record.getProjectId() != null) criteria.andProjectIdEqualTo(record.getProjectId());
        if (record.getStatus() != null) criteria.andStatusEqualTo(record.getStatus());
        if (record.getTaskId() != null) criteria.andTaskIdEqualTo(record.getTaskId());
        if (record.getProcessId() != null) criteria.andProcessIdEqualTo(record.getProcessId());
        if (record.getSearch() != null) { //按名称搜索
            criteria.andNoLike(record.getSearch());
        }
        if (record.getStatus() != null) { //按状态筛选
            criteria.andStatusEqualTo(record.getStatus());
        }
        return recordMapper.countByExample(recordExample);
    }
}
